#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry
import os
import logging
from .InitQtModule import *
# from JTK.jcore.Qt import *
from JTK.jcore.JPath import JPath
from . import QColorScheme as qcs
# reload(qcs)
from . import AovListWidget
# reload(AovListWidget)

# from unipath import Path
import maya.cmds as cmds
logger = logging.getLogger(__name__)

# __CURRENT_PATH__ = os.path.dirname(__file__)
from . import __file__ as _initpy_file
__CURRENT_PATH__ = os.path.dirname(os.path.realpath(_initpy_file))


class AOVLightGroupWidget(QWidget):
    maya_type_list = ['directionalLight', 'ambientLight', 'pointLight', 'spotLight', 'areaLight1', 'volumeLight']
    arnold_type_list = ['aiAreaLight', 'aiSkyDomeLight', 'aiPhotometricLight', 'aiLightPortal']
    light_type_list = maya_type_list + arnold_type_list
    default_list = ['default', 'KEY', 'HDRI', 'RIM', 'BACK', 'FILL', 'SKY']

    scheme = qcs.QColorScheme

    def __init__(self, parent=None, project=''):
        super(AOVLightGroupWidget, self).__init__(parent)
        self.setObjectName('AOVLightGroupWidget')

        self.setMaximumHeight(200)
        main_layout = QVBoxLayout()
        main_layout.setSpacing(5)
        main_layout.setContentsMargins(0, 0, 0, 0)
        label_layout = QHBoxLayout()
        label = QLabel('AOV Light Group')
        refresh_button = QToolButton()
        refresh_button.setMinimumSize(QSize(20, 20))
        icon_path = JPath(__CURRENT_PATH__).parent.child('data').child('icons').child('refresh.png')
        refresh_button.setIcon(QIcon(icon_path))
        # refresh_button.setStyleSheet('background-color: transparent;border-width: 0px;')
        label_layout.addWidget(label)
        label_layout.addWidget(refresh_button)
        self.list_widget = AovListWidget.AovListWidget(self)

        button_layout = QHBoxLayout()
        self.add_button = QPushButton(u'Add')
        self.set_button = QPushButton(u'Set')

        self.remove_button = QPushButton('Del')
        button_layout.addWidget(self.add_button)
        button_layout.addWidget(self.set_button)

        button_layout.addWidget(self.remove_button)

        check_layout = QHBoxLayout()
        self.merge_cbx = QCheckBox('Merge')
        self.half_cbx = QCheckBox('Half')
        self.prefix_cbx = QCheckBox('Prefix')

        check_layout.addWidget(self.merge_cbx)
        check_layout.addWidget(self.half_cbx)
        check_layout.addWidget(self.prefix_cbx)

        group_layout = QHBoxLayout()
        group_label = QLabel('GroupName')
        self.group_edit = QLineEdit()
        group_layout.addWidget(group_label)
        group_layout.addWidget(self.group_edit)

        main_layout.addLayout(label_layout)
        main_layout.addWidget(self.list_widget)
        main_layout.addLayout(button_layout)
        # main_layout.addLayout(check_layout)
        # main_layout.addLayout(group_layout)

        self.setLayout(main_layout)
        refresh_button.clicked.connect(self.default_aov_group)
        self.add_button.clicked.connect(self.add_light_group)
        self.set_button.clicked.connect(self.set_light_group)
        self.remove_button.clicked.connect(self.remove_light_group)

        scheme = self.scheme()
        scheme.setColor(QColor(120, 100, 80, 255), spread=5.5)
        scheme.applyStyle(self.add_button)
        scheme.setColor(QColor(100, 80, 120, 255), spread=5.5)
        scheme.applyStyle(self.set_button)
        scheme.setColor(QColor(120, 80, 80, 255), spread=5.5)
        scheme.applyStyle(self.remove_button)

        self.default_aov_group()

    def default_aov_group(self):
        self.list_widget.clear()
        for t in self.light_type_list:
            light_list = cmds.ls(type=t)
            # print light_list
            for light in light_list:
                light_group_name = cmds.getAttr('%s.aiAov' % light)
                if light_group_name in self.default_list:
                    self.default_list.remove(light_group_name)
                if light_group_name not in self.default_list:
                    if light_group_name not in self.list_widget.texts():
                        item = QListWidgetItem()
                        item.setText(light_group_name)
                        brush = QBrush()
                        brush.setColor(QColor(0, 255, 0))
                        item.setForeground(brush)
                        self.list_widget.addItem(item)
        self.list_widget.addItems(self.default_list)

    def add_light_group(self):
        result, check = QInputDialog.getText(self, 'AOV Light Group Name', u'New AOV Light Group Name：')
        if check:
            self.default_list.append(result)
            self.default_aov_group()

    def set_light_group(self):
        widget_sl = self.list_widget.selected_texts()
        light_sl = cmds.ls(sl=1) or []
        if widget_sl and light_sl:
            for light in light_sl:
                if self.isLight(light):
                    cmds.setAttr('%s.aiAov' % light, widget_sl[0], type='string')
                    logger.info(u'成功为%s指定aov light group为 %s'%(light, widget_sl[0]))

    def remove_light_group(self):
        widget_sl = self.list_widget.selected_texts() or []
        for g in widget_sl:
            if g == 'default':
                continue
            self.list_widget.takeText(g)
            for t in self.light_type_list:
                light_list = cmds.ls(type=t)
                for light in light_list:
                    light_group_name = cmds.getAttr('%s.aiAov' % light)
                    if g == light_group_name:
                        cmds.setAttr('%s.aiAov' % light, 'default', type='string')

    def select_aov_light(self):
        widget_sl = self.list_widget.selected_texts() or []
        group_light_list = []
        for g in widget_sl:
            for t in self.light_type_list:
                light_list = cmds.ls(type=t)
                for light in light_list:
                    light_group_name = cmds.getAttr('%s.aiAov' % light)
                    if g == light_group_name:
                        if cmds.objectType(light) != 'transform':
                            group_light_list.append(cmds.listRelatives(light,p=1)[0])
        cmds.select(group_light_list)

    def isLight(self, name):
        obj_type = cmds.objectType(name)
        if obj_type == 'transform':
            shape = cmds.listRelatives(name, s=1)
            if shape:
                if cmds.objectType(shape) in self.light_type_list:
                    return True
        elif obj_type in self.light_type_list:
            return True
        return False


if __name__ == "__main__":
    app = QApplication([])
    my_ui = AOVLightGroupWidget()
    my_ui.show()
    app.exec_()
